﻿using System;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.ComponentModel;

namespace Remote_Desktop_Administrator
{
    static class Connection
    {
        // our in-memory data store for connectsions and their details
        public static string[,] arrConnections = new string[50, 15];
        // keeps track of how many connections are added (NOT zero-based)
        public static int intRowConn = 0;
        // keeps track of how many fields in record are in use (zero-based, i.e. 10 means 11 actual items (0-10))
        public static int intColConn = 14;
        // default color depth
        private static int intDefaultColorD = 16;
        // our in-memory data store for folders and their properties
        public static string[,] arrFolders = new string[50, 5];
        // keeps track of how many folders are added (NOT zero-based)
        public static int intRowFold = 0;
        // keeps track of how many fields in record are in use (zero-based)
        public static int intColFold = 1;
        // designates whether to encrypt settings on save/load
        public static bool blnEncrypt = false;
        // shows dialog to user if their settings file is upgraded with new fields
        public static bool blnDisplaySaveMsg = false;

        //
        // Overview:
        // Updates an array to store connection parameters when new connection is added
        //        
        public static void SaveNewConnection(string strSvrName, string strConnName, string strUser, string strPass, string strDom, bool blnPrinters, bool blnDrives, bool blnClip, string strNote, string strColor, string strFolder, string strRes, string strPort)
        {
            try
            {
                arrConnections[intRowConn, 0] = Guid.NewGuid().ToString();
                arrConnections[intRowConn, 1] = strSvrName;
                arrConnections[intRowConn, 2] = strConnName;
                arrConnections[intRowConn, 3] = strUser;
                arrConnections[intRowConn, 4] = strPass;
                arrConnections[intRowConn, 5] = strDom;
                arrConnections[intRowConn, 6] = blnPrinters.ToString();
                arrConnections[intRowConn, 7] = blnDrives.ToString();
                arrConnections[intRowConn, 8] = blnClip.ToString();
                arrConnections[intRowConn, 9] = strNote;
                arrConnections[intRowConn, 10] = strColor;

                int intFi = FindFolderByName(strFolder);

                if (intFi != -1)
                    arrConnections[intRowConn, 11] = arrFolders[intFi, 0];
                else
                    arrConnections[intRowConn, 11] = "";

                arrConnections[intRowConn, 12] = strRes;

                arrConnections[intRowConn, 13] = "false";

                arrConnections[intRowConn, 14] = strPort;

                intRowConn++;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while adding new connection - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Moves through connection array and compares indexes (GUID) until server is found or end of array is reached
        //    
        public static int FindServer(string strGuid)
        {
            int intServerIndex = -1;

            for (int i = (intRowConn - 1); i >= 0; i--)
            {
                if (strGuid == arrConnections[i, 0])
                {
                    intServerIndex = i;
                    break;
                }
            }

            return intServerIndex;
        }

        //
        // Overview:
        // Populates the "new" connection form with selected index's info and allows user to save changes
        //    
        public static void UpdateConnection(string strGuid, TreeView treeViewMain)
        {
            // get our server index from guid
            int intIndex = FindServer(strGuid);
            if (intIndex != -1)
            {
                try
                {
                    // new instance of connection form class
                    ConnectionForm frmConn = new ConnectionForm();
                    // edit properties of new instance based on array
                    frmConn.prop_ServerName = arrConnections[intIndex, 1];
                    frmConn.prop_ConnectionName = arrConnections[intIndex, 2];
                    frmConn.prop_UserName = arrConnections[intIndex, 3];
                    frmConn.prop_Password = arrConnections[intIndex, 4];
                    frmConn.prop_Domain = arrConnections[intIndex, 5];
                    frmConn.prop_RedirectPrinters = arrConnections[intIndex, 6];
                    frmConn.prop_RedirectDrives = arrConnections[intIndex, 7];
                    frmConn.prop_RedirectClipboard = arrConnections[intIndex, 8];
                    frmConn.prop_Note = arrConnections[intIndex, 9];
                    frmConn.prop_Color = arrConnections[intIndex, 10];

                    int intFi = -1;
                    intFi = FindFolderByGuid(arrConnections[intIndex, 11]);
                    if (intFi != -1)
                        frmConn.prop_Folder = arrFolders[intFi, 1];

                    frmConn.prop_Res = arrConnections[intIndex, 12];

                    if (frmConn.prop_Port != arrConnections[intIndex, 14])
                    {
                        frmConn.prop_Port = arrConnections[intIndex, 14];
                        MessageBox.Show("Port changes will only take effect on next connection attempt...", "Port changed...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                    // misc properties
                    frmConn.Text = "Edit Connection";
                    frmConn.prop_UpdateConnection = true;
                    frmConn.prop_ExistingConnectionIndex = intIndex;
                    frmConn.ReceiveTreeViewRef(treeViewMain);
                    // show form
                    frmConn.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Error - unable to find sever...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Commits changes from edit form to array for connection in question
        //
        public static void SaveConnectionChanges(int intIndex, string strSvrName, string strConnName, string strUser, string strPass, string strDom, bool blnPrinters, bool blnDrives, bool blnClip, string strNote, string strColor, string strFolder, string strRes, string strPort)
        {
            try
            {
                arrConnections[intIndex, 1] = strSvrName;
                arrConnections[intIndex, 2] = strConnName;
                arrConnections[intIndex, 3] = strUser;
                arrConnections[intIndex, 4] = strPass;
                arrConnections[intIndex, 5] = strDom;
                arrConnections[intIndex, 6] = blnPrinters.ToString();
                arrConnections[intIndex, 7] = blnDrives.ToString();
                arrConnections[intIndex, 8] = blnClip.ToString();
                arrConnections[intIndex, 9] = strNote;
                arrConnections[intIndex, 10] = strColor;

                int intFi = FindFolderByName(strFolder);

                if (intFi != -1)
                {
                    arrConnections[intIndex, 11] = arrFolders[intFi, 0];
                }
                else
                {
                    arrConnections[intIndex, 11] = "";
                }

                arrConnections[intIndex, 12] = strRes;

                arrConnections[intIndex, 14] = strPort;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Deletes the selected item from array and shifts data accordingly
        //
        public static void DeleteConnection(string strGuid, TreeView treeViewMain)
        {
            // find our server guid
            int intIndex = FindServer(strGuid);
            // iterate through array and copy the i+1 to the i element
            if (intIndex != -1)
            {
                //arrConnections.GetLength(0) - 1
                for (int i = intIndex; i < intRowConn; i++)
                {
                    for (int x = 0; x <= intColConn; x++)
                    {
                        arrConnections[i, x] = arrConnections[i + 1, x];
                    }
                }
                // shrink our element counter
                intRowConn--;
                // refresh the tree
                RefreshTreeView(treeViewMain);
            }
            else
            {
                MessageBox.Show("Error unable to find server...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Takes treeview and refreshes its view when connections are changed
        //  
        public static void RefreshTreeView(TreeView treeViewMain)
        {
            // clear it all out!
            treeViewMain.Nodes.Clear();

            // create our "default" node for unassigned connections
            TreeNode TnDef = new TreeNode();
            TnDef.Text = "(Default)";
            TnDef.Tag = "xxx_DefaultNode_xxx";
            TnDef.ImageIndex = 0;
            treeViewMain.Nodes.Add(TnDef);

            for (int f = 0; f < intRowFold; f++)
            {
                TreeNode TnFold = new TreeNode();
                TnFold.Name = arrFolders[f, 0];
                TnFold.Text = arrFolders[f, 1];
                TnFold.Tag = "Folder";
                TnFold.ImageIndex = 0;
                treeViewMain.Nodes.Add(TnFold);
            }

            // iterate through connections array
            for (int c = 0; c < intRowConn; c++)
            {
                // iterate through folder array for each connection, attempting to find matching guids
                for (int f = 0; f < intRowFold; f++)
                {
                    // if match found ... add it to 
                    if (arrConnections[c, 11] == arrFolders[f, 0])
                    {
                        TreeNode[] TnSearch = treeViewMain.Nodes.Find(arrFolders[f, 0], true);

                        if (TnSearch.Length > 0)
                        {
                            TreeNode TnConn = new TreeNode();
                            TnConn.Name = arrConnections[c, 0];
                            TnConn.Text = arrConnections[c, 2];
                            TnConn.Tag = "Connection";
                            TnConn.ImageIndex = 1;
                            TnSearch[0].Nodes.Add(TnConn);

                            // highlights connection if "connected"
                            if (Convert.ToBoolean(arrConnections[c, 13]))
                            {
                                TnConn.BackColor = Color.DarkGray;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Error - unable to find folder in tree.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }

            for (int z = 0; z < intRowConn; z++)
            {
                if (arrConnections[z, 11] == "")
                {
                    TreeNode TnConn = new TreeNode();
                    TnConn.Name = arrConnections[z, 0];
                    TnConn.Text = arrConnections[z, 2];
                    TnConn.Tag = "Connection";
                    TnConn.ImageIndex = 1;
                    TnDef.Nodes.Add(TnConn);

                    // highlights connection if "connected"
                    if (Convert.ToBoolean(arrConnections[z, 13]))
                    {
                        TnConn.BackColor = Color.DarkGray;
                    }
                }
            }

            // sort view
            treeViewMain.Sort();
            // expand all nodes
            treeViewMain.ExpandAll();
        }

        //
        // Overview:
        // Takes rdp control and disconnects session
        //  
        public static void DisconnectSession(AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1, MainForm frm1)
        {
            try
            {
                Ax1.Disconnect();
                frm1.Controls.Remove(Ax1);
                Ax1.Dispose();
            }
            catch (Exception)
            {
                // silent so as not to alarm user...
            }
        }

        //
        // Overview:
        // Takes rdp control ref & connects session
        //  
        public static void ConnectSession(AxMSTSCLib.AxMsRdpClient6NotSafeForScripting Ax1, SplitContainer Sc1, int i, bool C2c, bool blnCreds)
        {
            try
            {
                int intColorD = DetermineColorDepth(arrConnections[i, 10]);

                Sc1.Panel2.Controls.Add(Ax1);
                Ax1.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom) | AnchorStyles.Left) | AnchorStyles.Right)));
                Ax1.Enabled = true;
                Ax1.Location = new System.Drawing.Point(0, 0);
                Ax1.Name = "Ax--" + arrConnections[i, 0];
                Ax1.Size = new System.Drawing.Size(Sc1.Panel2.Width, Sc1.Panel2.Height);
                Ax1.BringToFront();
                Ax1.Tag = arrConnections[i, 0];
                Ax1.Server = arrConnections[i, 1];
                if (blnCreds)
                {
                    Ax1.UserName = arrConnections[i, 3];
                    Ax1.AdvancedSettings7.ClearTextPassword = arrConnections[i, 4];
                    Ax1.Domain = arrConnections[i, 5];
                }
                Ax1.AdvancedSettings7.RedirectPrinters = Convert.ToBoolean(arrConnections[i, 6]);
                Ax1.AdvancedSettings7.RedirectDrives = Convert.ToBoolean(arrConnections[i, 7]);
                Ax1.AdvancedSettings7.RedirectClipboard = Convert.ToBoolean(arrConnections[i, 8]);
                Ax1.AdvancedSettings7.ConnectToAdministerServer = C2c;
                Ax1.AdvancedSettings7.RDPPort = Convert.ToInt32(arrConnections[i, 14]);

                if (intColorD != -1)
                    Ax1.ColorDepth = intColorD;
                else
                    Ax1.ColorDepth = intDefaultColorD;

                if (arrConnections[i, 12] == "Fill pane" || arrConnections[i, 12] == "")
                {
                    Ax1.DesktopHeight = Ax1.Height;
                    Ax1.DesktopWidth = Ax1.Width;
                }
                if (arrConnections[i, 12] == "800 x 600")
                {
                    Ax1.DesktopWidth = 800;
                    Ax1.DesktopHeight = 600;
                }
                if (arrConnections[i, 12] == "1024 x 768")
                {
                    Ax1.DesktopWidth = 1024;
                    Ax1.DesktopHeight = 768;
                }

                Ax1.ConnectingText = "Connecting to " + arrConnections[i, 2] + " ... ";
                Ax1.DisconnectedText = "Disconnected from " + arrConnections[i, 2] + " ... ";

                Ax1.Connect();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while attempting to connect - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Takes main form as ref and finds appropriate rdp control related to guid of connection
        // 
        public static AxMSTSCLib.AxMsRdpClient6NotSafeForScripting FindRdpControl(MainForm frm1, string guid1)
        {
            Control[] Ax1 = frm1.Controls.Find("Ax--" + guid1, true);

            if (Ax1.Length > 0)
            {
                //foreach (AxMSTSCLib.AxMsRdpClient6NotSafeForScripting x in Ax1)
                //{
                //    MessageBox.Show(x.Tag.ToString());
                //}
                return (AxMSTSCLib.AxMsRdpClient6NotSafeForScripting)Ax1[0];
            }
            else
            {
                return null;
            }
        }

        //
        // Overview:
        // Writes connection array to text file for later use
        //
        public static bool SaveSettings(string strFn)
        {
            bool blnSuccess = false;
            string strFin = strFn + ".tmp";
            StreamWriter sw;

            Encryption.strSecretKey = "";
            CryptKeyForm frmCryptKey = new CryptKeyForm();
            frmCryptKey.ShowDialog();

            if (blnEncrypt)
            {
                StreamWriter sw1 = new StreamWriter(strFin);
                sw = sw1;
            }
            else
            {
                StreamWriter sw1 = new StreamWriter(strFn);
                sw = sw1;
            }

            try
            {
                //iterate thru arrays - first row, then each col for each row
                for (int i = 0; i < intRowConn; i++)
                {
                    for (int x = 0; x <= intColConn; x++)
                    {
                        //init variables for taking about commas and newlines
                        string noCommaConn = "";
                        string noNewLineConn = "";

                        //check each column and remove commas...then newlines
                        noCommaConn = arrConnections[i, x].Replace(",", "[-comma-]");
                        noNewLineConn = noCommaConn.Replace(Environment.NewLine, "[-newline-]");

                        //for the isconnected flag for highlights in tree view
                        //we want it to be disconnected in the settings file to make loads are clean!
                        if (x == 13)
                            noNewLineConn = "false";

                        //write to file the cleaned-up result
                        sw.Write(noNewLineConn);
                        
                        //want to leave comma off last item!
                        if (x < intColConn)
                            sw.Write(",");
                    }
                    //move to next line to prep for next record
                    if (i < intRowConn - 1)
                        sw.Write(Environment.NewLine);
                }

                //again...just iterate thru cols for each row and clean up special chars that will cause trouble
                for (int i = 0; i < intRowFold; i++)
                {
                    //write newline on first attempt
                    if (i == 0)
                        sw.Write(Environment.NewLine);

                    for (int x = 0; x <= intColFold; x++)
                    {
                        string noCommaFold = "";

                        noCommaFold = arrFolders[i, x].Replace(",", "[-comma-]");

                        sw.Write(noCommaFold);
                        //looking to leave comma off end of line
                        if (x < intColFold)
                            sw.Write(",");
                    }
                    if (i < intRowFold - 1)
                        sw.Write(Environment.NewLine);
                }

                blnSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while attempting save - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                blnSuccess = false;
            }

            sw.Close();
            sw.Dispose();

            if (blnEncrypt)
            {
                try
                {
                    if (Encryption.strSecretKey != "")
                    {
                        Encryption.strFileIn = strFin;
                        Encryption.strFileOut = strFn;
                        Encryption.EncryptFile();
                    }
                    else
                    {
                        MessageBox.Show("Encryption skipped due to invalid key.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while attempting to encrypt settings file - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    blnSuccess = false;
                }
            }

            if (blnEncrypt)
            {
                try
                {
                    File.Delete(strFin);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while attempting to delete temp file - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    blnSuccess = false;
                }
            }

            return blnSuccess;
        }

        //
        // Overview:
        // Reads text file into arrays
        //
        public static bool LoadSettings(string strFn)
        {
            bool blnSuccess = false;
            string strFout = strFn + ".tmp";

            Encryption.strSecretKey = "";
            CryptKeyForm frmCryptKey = new CryptKeyForm();
            frmCryptKey.ShowDialog();

            if (blnEncrypt)
            {
                try
                {
                    if (Encryption.strSecretKey != "")
                    {
                        Encryption.strFileIn = strFn;
                        Encryption.strFileOut = strFout;
                        Encryption.DecryptFile();
                    }
                    else
                    {
                        MessageBox.Show("Decryption skipped.");
                    }
                }
                catch
                {
                    //MessageBox.Show("Error while attempting to decrypt settings file - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return blnSuccess;
                }
            }

            try
            {
                List<string[]> lstLines = new List<string[]>();
                if (blnEncrypt)
                {
                    lstLines = parseCSV(strFout);
                }
                else
                {
                    lstLines = parseCSV(strFn);
                }
                foreach (string[] line in lstLines)
                {
                    if (line.Length == (intColConn + 1))
                    {
                        for (int i = 0; i <= intColConn; i++)
                        {
                            line[i] = line[i].Replace("[-comma-]", ",");
                            line[i] = line[i].Replace("[-newline-]", Environment.NewLine);
                        }
                        LoadConnection(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10], line[11], line[12], line[13], line[14]);
                    }
                    else if (line.Length == 13)
                    {
                        for (int i = 0; i < 13; i++)
                        {
                            if (i < 13)
                            {
                                line[i] = line[i].Replace("[-comma-]", ",");
                                line[i] = line[i].Replace("[-newline-]", Environment.NewLine);
                            }
                        }
                        //feature add for isConnected flag
                        string strIsConnected = "false";
                        //feature add for custom rdp port
                        string strPort = "3389";
                        //display diag to user to save file after "upgrade" of settings file...
                        blnDisplaySaveMsg = true;
                        LoadConnection(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10], line[11], line[12], strIsConnected, strPort);
                    }
                    else if (line.Length == (intColFold + 1))
                    {
                        for (int i = 0; i <= intColFold; i++)
                        {
                            line[i] = line[i].Replace("[-comma-]", ",");
                        }
                        LoadFolder(line[0],line[1]);
                    }
                    else
                    {
                        //MessageBox.Show("Invalid line detected in settings file...was someone messing with it?? \nPassing by invalid line...");
                    }
                }

                blnSuccess = true;
                //display message about upgrade, if appropriate
                if (blnDisplaySaveMsg)
                    MessageBox.Show("Please save over your old settings file after successful load", "Older settings file detected...", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading file - " + ex.Message);
            }

            if (blnEncrypt)
            {
                try
                {
                    File.Delete(strFout);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while attempting to delete temp file - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            return blnSuccess;
        }

        //
        // Overview:
        // Simple parser for csv file
        // Code snippet adapted from: http://www.switchonthecode.com/tutorials/building-a-simple-csv-parser-in-csharp
        //           
        public static List<string[]> parseCSV(string path)
        {
            List<string[]> parsedData = new List<string[]>();

            try
            {
                using (StreamReader readFile = new StreamReader(path))
                {
                    string line;
                    string[] row;


                    while ((line = readFile.ReadLine()) != null)
                    {
                        row = line.Split(',');
                        parsedData.Add(row);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return parsedData;
        }

        //
        // Overview:
        // Updates an array to store connection parameters when file is loaded
        //        
        public static void LoadConnection(string strGuid, string strSvrName, string strConnName, string strUser, string strPass, string strDom, string strPrinters, string strDrives, string strClip, string strNote, string strColor, string strFolderGuid, string strRes, string strIsConnected, string strPort)
        {
            try
            {
                arrConnections[intRowConn, 0] = strGuid;
                arrConnections[intRowConn, 1] = strSvrName;
                arrConnections[intRowConn, 2] = strConnName;
                arrConnections[intRowConn, 3] = strUser;
                arrConnections[intRowConn, 4] = strPass;
                arrConnections[intRowConn, 5] = strDom;
                arrConnections[intRowConn, 6] = strPrinters;
                arrConnections[intRowConn, 7] = strDrives;
                arrConnections[intRowConn, 8] = strClip;
                arrConnections[intRowConn, 9] = strNote;
                arrConnections[intRowConn, 10] = strColor;
                arrConnections[intRowConn, 11] = strFolderGuid;
                arrConnections[intRowConn, 12] = strRes;
                arrConnections[intRowConn, 13] = strIsConnected;
                arrConnections[intRowConn, 14] = strPort;

                intRowConn++;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while loading connection - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Load folder to array
        //
        public static void LoadFolder(string strGuid, string strFN)
        {
            try
            {
                arrFolders[intRowFold, 0] = strGuid;
                arrFolders[intRowFold, 1] = strFN;
                intRowFold++;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during folder load - " + ex.Message);
            }
        }

        //
        // Overview:
        // Based on selection in options form, determines color depth
        //
        public static int DetermineColorDepth(string CboSelection)
        {
            int x = -1;

            if (CboSelection == "8-bit")
                x = 8;
            if (CboSelection == "16-bit")
                x = 16;
            if (CboSelection == "24-bit")
                x = 24;

            return x;
        }

        //
        // Overview:
        // Save new folder to array
        //
        public static void SaveNewFolder(string strFN)
        {
            try
            {
                arrFolders[intRowFold, 0] = Guid.NewGuid().ToString();
                arrFolders[intRowFold, 1] = strFN;
                intRowFold++;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during folder save - " + ex.Message);
            }
        }

        //
        // Overview:
        // Moves through folder array and compares names until folder is found or end of array is reached
        //    
        public static int FindFolderByName(string strFoldName)
        {
            int intFolderIndex = -1;

            for (int i = (intRowFold - 1); i >= 0; i--)
            {
                if (strFoldName == arrFolders[i, 1])
                {
                    intFolderIndex = i;
                    break;
                }
            }

            return intFolderIndex;
        }

        //
        // Overview:
        // Moves through folder array and compares guids until folder is found or end of array is reached
        //    
        public static int FindFolderByGuid(string strGuid)
        {
            int intFolderIndex = -1;

            for (int i = (intRowFold - 1); i >= 0; i--)
            {
                if (strGuid == arrFolders[i, 0])
                {
                    intFolderIndex = i;
                    break;
                }
            }

            return intFolderIndex;
        }

        //
        // Overview:
        // Refreshes combo box of folder names
        // 
        public static void RefreshCboFolders(ComboBox Cb1)
        {
            Cb1.Items.Clear();

            for (int x = 0; x < Connection.intRowFold; x++)
            {
                Cb1.Items.Add(Connection.arrFolders[x, 1]);
                Cb1.Sorted = true;
            }
        }

        //
        // Overview:
        // Deletes the selected folder from the array
        //
        public static void DeleteFolder(string strGuid, TreeView treeViewMain)
        {
            // find our folder index by guid
            int intIndex = FindFolderByGuid(strGuid);
            // iterate through array and copy the i+1 to the i element
            if (intIndex != -1)
            {
                for (int i = intIndex; i < intRowFold; i++)
                {
                    for (int x = 0; x <= intColFold; x++)
                    {
                        arrFolders[i, x] = arrFolders[i + 1, x];
                    }
                }
                
                // shrink our element counter
                intRowFold--;

                // remove references to this folder guid
                for (int c = 0; c < intRowConn; c++)
                {
                    if (arrConnections[c, 11] == strGuid)
                    {
                        arrConnections[c, 11] = "";
                    }
                }

                // refresh the tree
                RefreshTreeView(treeViewMain);
            }
            else
            {
                MessageBox.Show("Error unable to delete folder...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //
        // Overview:
        // Renames selected folder
        //
        public static void RenameFolder(string strGuid, string strFolder, TreeView treeViewMain)
        {
            // find our server guid
            int intIndex = FindFolderByGuid(strGuid);
            
            // iterate through array and copy the i+1 to the i element
            if (intIndex != -1)
            {
                for (int i = 0; i < intRowFold; i++)
                {
                    // make sure there are no duplicate names
                    if (strFolder == arrFolders[i, 1])
                    {
                        // if name already exists, exit method
                        MessageBox.Show("Folder name already exists. Choose another name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }                    
                }
                
                // assign the changed name
                arrFolders[intIndex, 1] = strFolder;     

                // refresh the tree
                RefreshTreeView(treeViewMain);
            }
            else
            {
                MessageBox.Show("Error unable to rename folder...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}